package com.lfx.concurrent;


public class Data {

    private final char[] data;

    private final ReadWriteLock lock=new ReadWriteLock() ;

    public Data(int size) {
        this.data =new char[size];
    }


    public char[] read() throws InterruptedException {
        lock.readLock();
        try{
            return doRead();
        }finally {
            lock.readUnlock();
        }
    }

    private char[] doRead() throws InterruptedException {
        char[] newbuf = new char[data.length];
        for (int i = 0; i < data.length; i++) {
            newbuf[i]=data[i];
        }
        slowly();
        return newbuf;
    }


    public void  writer(char c) throws InterruptedException {
        lock.writerLock();
        try{
            doWrite(c);
        }finally {
            lock.writerUnLock();
        }
    }

    private void doWrite(char c) throws InterruptedException {
        for (int i = 0; i < data.length; i++) {
            data[i]=c;
            slowly();
        }
    }


    private void slowly() throws InterruptedException {
        Thread.sleep(1000L);
    }
}
